package com.db.patterns.client;

import cm.db.patterns.commands.Command;
import cm.db.patterns.commands.UpdateCommand;

import com.db.patterns.caches.Cache;

public class UpdatableCache implements Cache{
	Cache clientCache;
	ServerCache serverCache;
	volatile private boolean working;
	
	public UpdatableCache(Cache clientCache, ServerCache serverCache) {
		this.clientCache = clientCache;
		this.serverCache = serverCache;
	}
	
	public void start() {
		this.working = true;
		new Thread(new Updater()).start();
	}
	
	private class Updater implements Runnable {

		@Override
		public void run() {
			while(working) {
				Command command = serverCache.getUpdates();
				if (command != null) {
					// is not good practice
					if (command instanceof UpdateCommand) {
						UpdateCommand c = (UpdateCommand)command;
						clientCache.put(c.getKey(), c.getValue());
					}
				}
			}
		}
		
	}
	
	public void stop() {
		this.working = false;
	}

	@Override
	public Object get(String key) {
		return clientCache.get(key);
	}

	@Override
	public void put(String key, Object value) {
		clientCache.put(key, value);
	}
}
